package com.sneaker.shower.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import com.google.common.collect.Lists;
import com.sneaker.shower.entity.dto.WxCommonReqDTO;
import com.sneaker.shower.service.WxMaPortalService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Hechangjian
 * @version 1.0
 * @className WxMaPortalServiceImpl
 * @date 2019/07/26 20:59
 * @description
 * @program bath
 */
@Service
@Slf4j
public class WxMaPortalServiceImpl implements WxMaPortalService {

    private final WxMaService wxMaService;
    @Value("${wx.mp.appId}")
    private String mpAppId;
    @Value("${wx.ma.appId}")
    private String maAppId;

    public WxMaPortalServiceImpl(WxMaService wxMaService) {
        this.wxMaService = wxMaService;
    }

    @Override
    public String verify(WxCommonReqDTO wxCommonReqDTO) {
        log.info("接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                wxCommonReqDTO.getSignature(), wxCommonReqDTO.getTimestamp(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getEchostr());
        if (StringUtils.isAnyBlank(wxCommonReqDTO.getSignature(), wxCommonReqDTO.getTimestamp(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getEchostr())) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        if (wxMaService.checkSignature(wxCommonReqDTO.getTimestamp(), wxCommonReqDTO.getNonce(), wxCommonReqDTO.getSignature())) {
            return wxCommonReqDTO.getEchostr();
        }
        return "非法请求";
    }

    @Override
    public void sendTemplateMsg(String templateId, List<String> params, String openId, String first, String remark) {
        WxMaUniformMessage wxMaUniformMessage = WxMaUniformMessage.builder()
                .templateId(templateId).appid(mpAppId)
                .miniProgram(new WxMaUniformMessage.MiniProgram(maAppId, "pages/home/main", true, true))
                .isMpTemplateMsg(true)
                .toUser(openId)
                .page("pages/home/main")
                .data(buildUniformMessage(params, first, remark))
                .build();
        try {
            wxMaService.getMsgService().sendUniformMsg(wxMaUniformMessage);
        } catch (WxErrorException e) {
            log.info("小程序模板消息发送失败,fromId:{},toUser:{},消息内容:{}", templateId, openId, params);
        }
    }

    private List<WxMaTemplateData> buildUniformMessage(List<String> params, String first, String remark) {
        List<WxMaTemplateData> dataList = Lists.newArrayList();
        for (int i = 0; i < params.size(); i++) {
            WxMaTemplateData wxMaTemplateData = new WxMaTemplateData();
            wxMaTemplateData.setName("keyword" + (i + 1));
            wxMaTemplateData.setValue(params.get(i));
            dataList.add(wxMaTemplateData);
        }
        WxMaTemplateData firstData = new WxMaTemplateData();
        firstData.setName("first");
        firstData.setValue(first);
        dataList.add(firstData);
        WxMaTemplateData remarkData = new WxMaTemplateData();
        remarkData.setName("remark");
        remarkData.setValue(remark);
        dataList.add(remarkData);
        return dataList;
    }
}
